#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include "record.h"

// 计算序列化一行记录所需的字节数
// 参数：
// - s: 表结构
// - vals: 字段值数组
// 返回值：所需字节数
static int need_len(const TableSchema *s, const char *const *vals){
    int n = sizeof(RowHeader);
    for (int i=0; i<s->ncols; i++){
        if (s->cols[i].type==TYPE_INT) {
            n += 4; // INT类型占4字节
        } else { // varchar
            int L = (int)strlen(vals[i]);
            if (L > s->cols[i].max_len) L = s->cols[i].max_len;
            n += 2 + L; // uint16_t 长度 + 数据
        }
    }
    return n;
}

// 将行记录序列化为二进制数据
// 参数：
// - s: 表结构
// - vals: 字段值数组
// - buf: 输出缓冲区，如果为NULL则仅计算所需空间
// - cap: 缓冲区容量
// 返回值：成功返回序列化的字节数，失败返回-1
int serialize_row(const TableSchema *s, const char *const *vals, uint8_t *buf, int cap){
    // 增强参数验证
    if (!s) {
        fprintf(stderr, "serialize_row: NULL table schema\n");
        return -1;
    }
    if (!vals) {
        fprintf(stderr, "serialize_row: NULL values array\n");
        return -1;
    }
    if (s->ncols <= 0 || !s->cols) {
        fprintf(stderr, "serialize_row: Invalid table schema - no columns\n");
        return -1;
    }

    // 计算所需空间
    int need = need_len(s, vals);
    if (need <= 0) {
        fprintf(stderr, "serialize_row: Failed to calculate needed length (need=%d)\n", need);
        return -1;
    }
    
    if (!buf) {
        return need;  // 仅计算空间
    }
    
    if (cap < need) {
        fprintf(stderr, "serialize_row: Buffer too small (need=%d, cap=%d)\n", need, cap);
        return -1;
    }

    // 初始化行头
    RowHeader *hdr = (RowHeader*)buf;
    hdr->deleted = 0;
    int off = sizeof(RowHeader);

    // 序列化每一列
    for (int i=0; i<s->ncols; i++){
        // 验证当前值是否有效
        if (!vals[i]) {
            fprintf(stderr, "serialize_row: NULL value for column %d\n", i);
            return -1;
        }
        
        if (s->cols[i].type == TYPE_INT){
            // 安全的类型转换
            char* endptr = NULL;
            long long v = strtoll(vals[i], &endptr, 10);
            
            // 检查转换是否成功
            if (endptr == vals[i] || *endptr != '\0') {
                fprintf(stderr, "serialize_row: Invalid integer value '%s' for column %d\n", vals[i], i);
                return -2;
            }
            
            // 确保值在INT范围内
            if (v > INT_MAX || v < INT_MIN) {
                fprintf(stderr, "serialize_row: Integer value out of range '%s' for column %d\n", vals[i], i);
                return -2;
            }
            
            int int_val = (int)v;
            memcpy(buf + off, &int_val, 4); 
            off += 4;
        } else if (s->cols[i].type == TYPE_VARCHAR) {
            uint16_t L = (uint16_t)strlen(vals[i]);
            
            // 检查长度是否超过最大限制
            if (s->cols[i].max_len > 0 && L > s->cols[i].max_len) {
                L = s->cols[i].max_len;
                fprintf(stderr, "serialize_row: Truncating VARCHAR value for column %d (max_len=%d)\n", i, s->cols[i].max_len);
            }
            
            memcpy(buf + off, &L, 2); 
            off += 2;
            memcpy(buf + off, vals[i], L); 
            off += L;
        } else {
            // 其他类型暂时按照VARCHAR处理，但添加类型警告
            fprintf(stderr, "serialize_row: Unsupported column type %d, treating as VARCHAR\n", s->cols[i].type);
            
            uint16_t L = (uint16_t)strlen(vals[i]);
            if (s->cols[i].max_len > 0 && L > s->cols[i].max_len) {
                L = s->cols[i].max_len;
            }
            memcpy(buf + off, &L, 2); 
            off += 2;
            memcpy(buf + off, vals[i], L); 
            off += L;
        }
    }
    
    return need;
}

// 将二进制行记录反序列化为文本值
// 参数：
// - s: 表结构
// - buf: 二进制数据缓冲区
// - len: 二进制数据长度
// - out: 输出文本值数组
// - cap: 输出数组容量
// 返回值：成功返回0，失败返回负错误码
int deserialize_row(const TableSchema *s, const uint8_t *buf, int len, char **out, int cap){
    // 增强参数验证
    if (!s) {
        fprintf(stderr, "deserialize_row: NULL table schema\n");
        return -1;
    }
    if (!buf) {
        fprintf(stderr, "deserialize_row: NULL buffer\n");
        return -1;
    }
    if (!out) {
        fprintf(stderr, "deserialize_row: NULL output array\n");
        return -1;
    }
    
    // 检查输出容量是否足够
    if (cap < s->ncols) {
        fprintf(stderr, "deserialize_row: Output array capacity too small (need=%d, cap=%d)\n", s->ncols, cap);
        return -1;
    }
    
    // 检查缓冲区长度是否足够
    if (len < (int)sizeof(RowHeader)) {
        fprintf(stderr, "deserialize_row: Buffer too short for row header\n");
        return -2;
    }
    
    // 检查行是否已删除
    const RowHeader *hdr = (const RowHeader*)buf;
    if (hdr->deleted) {
        fprintf(stderr, "deserialize_row: Attempting to deserialize deleted row\n");
        return -3;
    }

    int off = sizeof(RowHeader);
    for (int i=0; i<s->ncols; i++){
        if (s->cols[i].type == TYPE_INT){
            // 检查是否有足够的空间读取整数值
            if (off + 4 > len) {
                fprintf(stderr, "deserialize_row: Not enough data to read INT value at column %d\n", i);
                // 释放已分配的内存
                for (int j=0; j<i; j++) {
                    free(out[j]);
                }
                return -4;
            }
            
            int v;
            memcpy(&v, buf + off, 4);
            off += 4;
            
            // 使用局部变量而不是静态数组，避免线程安全问题
            char tmp[32];
            snprintf(tmp, sizeof(tmp), "%d", v);
            
            out[i] = strdup(tmp);
            if (!out[i]) {
                fprintf(stderr, "deserialize_row: Failed to allocate memory for INT value at column %d\n", i);
                // 释放已分配的内存
                for (int j=0; j<i; j++) {
                    free(out[j]);
                }
                return -7;
            }
        } else {
            // 检查是否有足够的空间读取字符串长度
            if (off + 2 > len) {
                fprintf(stderr, "deserialize_row: Not enough data to read VARCHAR length at column %d\n", i);
                // 释放已分配的内存
                for (int j=0; j<i; j++) {
                    free(out[j]);
                }
                return -5;
            }
            
            uint16_t L;
            memcpy(&L, buf + off, 2);
            off += 2;
            
            // 检查是否有足够的空间读取字符串内容
            if (off + L > len) {
                fprintf(stderr, "deserialize_row: Not enough data to read VARCHAR content at column %d\n", i);
                // 释放已分配的内存
                for (int j=0; j<i; j++) {
                    free(out[j]);
                }
                return -6;
            }
            
            // 分配内存存储字符串
            out[i] = (char*)malloc(L + 1);
            if (!out[i]) {
                fprintf(stderr, "deserialize_row: Failed to allocate memory for VARCHAR value at column %d\n", i);
                // 释放已分配的内存
                for (int j=0; j<i; j++) {
                    free(out[j]);
                }
                return -7;
            }
            
            // 复制字符串内容并添加终止符
            memcpy(out[i], buf + off, L);
            out[i][L] = '\0';
            off += L;
        }
    }
    
    return 0;
}
